<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1000">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="180px"
      v-loading="formLoading"
    >
      <el-form-item label="用户" prop="userId">
        <el-select v-model="formData.userId" clearable filterable placeholder="请选择">
          <el-option
            v-for="user in userOptions"
            :key="user.id"
            :label="user.nickname"
            :value="user.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单" prop="orderId">
        <el-input v-model="formData.orderId" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="购物车项" prop="cartId">
        <el-input v-model="formData.cartId" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="商品SPU" prop="spuId">
        <el-select v-model="formData.spuId" clearable filterable placeholder="请选择">
          <el-option v-for="spu in spuOptions" :key="spu.id" :label="spu.name" :value="spu.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品SPU名称" prop="spuName">
        <el-input v-model="formData.spuName" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="商品属性数组" prop="properties">
        <el-input v-model="formData.properties" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="商品图片" prop="picUrl">
        <el-input v-model="formData.picUrl" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="购买数量" prop="count">
        <el-input v-model="formData.count" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="是否评价" prop="commentStatus">
        <el-select v-model="formData.commentStatus" placeholder="请选择">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品原价" prop="price">
        <el-input v-model="formData.price" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="商品级优惠（总）" prop="discountPrice">
        <el-input v-model="formData.discountPrice" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="运费金额" prop="deliveryPrice">
        <el-input v-model="formData.deliveryPrice" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="订单调价（总）" prop="adjustPrice">
        <el-input v-model="formData.adjustPrice" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="子订单实付金额（总）" prop="payPrice">
        <el-input v-model="formData.payPrice" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="优惠劵减免金额" prop="couponPrice">
        <el-input v-model="formData.couponPrice" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="积分抵扣的金额" prop="pointPrice">
        <el-input v-model="formData.pointPrice" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="使用的积分" prop="usePoint">
        <el-input v-model="formData.usePoint" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="赠送的积分" prop="givePoint">
        <el-input v-model="formData.givePoint" placeholder="请输入" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { OrderItemApi, OrderItem } from '@/api/recycling/orderitem'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import * as UserApi from '@/api/system/user'
import { ReProductSpuApi, ReProductSpu } from '@/api/recycling/recyproductspu'
/** 回收订单明细 表单 */
defineOptions({ name: 'OrderItemForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const userOptions = ref()
const spuOptions = ref()
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  userId: undefined,
  orderId: undefined,
  cartId: undefined,
  spuId: undefined,
  spuName: undefined,
  properties: undefined,
  picUrl: undefined,
  count: undefined,
  commentStatus: undefined,
  price: undefined,
  discountPrice: undefined,
  deliveryPrice: undefined,
  adjustPrice: undefined,
  payPrice: undefined,
  couponPrice: undefined,
  pointPrice: undefined,
  usePoint: undefined,
  givePoint: undefined
})
const formRules = reactive({
  userId: [{ required: true, message: '用户编号不能为空', trigger: 'blur' }],
  orderId: [{ required: true, message: '订单编号不能为空', trigger: 'blur' }],
  spuId: [{ required: true, message: '商品 SPU 编号不能为空', trigger: 'blur' }],
  spuName: [{ required: true, message: '商品 SPU 名称不能为空', trigger: 'blur' }],
  count: [{ required: true, message: '购买数量不能为空', trigger: 'blur' }],
  commentStatus: [{ required: true, message: '是否评价不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '商品原价（单），单位：分不能为空', trigger: 'blur' }],
  discountPrice: [
    { required: true, message: '商品级优惠（总），单位：分不能为空', trigger: 'blur' }
  ],
  deliveryPrice: [{ required: true, message: '运费金额，单位：分不能为空', trigger: 'blur' }],
  adjustPrice: [{ required: true, message: '订单调价（总），单位：分不能为空', trigger: 'blur' }],
  payPrice: [
    {
      required: true,
      message: '子订单实付金额（总），不算主订单分摊金额，单位：分不能为空',
      trigger: 'blur'
    }
  ],
  couponPrice: [{ required: true, message: '优惠劵减免金额，单位：分不能为空', trigger: 'blur' }],
  pointPrice: [{ required: true, message: '积分抵扣的金额不能为空', trigger: 'blur' }],
  usePoint: [{ required: true, message: '使用的积分不能为空', trigger: 'blur' }],
  givePoint: [{ required: true, message: '赠送的积分不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  userOptions.value = await UserApi.getSimpleUserList()
  spuOptions.value = (await ReProductSpuApi.getReProductSpuPage({})).list
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await OrderItemApi.getOrderItem(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OrderItem
    if (formType.value === 'create') {
      await OrderItemApi.createOrderItem(data)
      message.success(t('common.createSuccess'))
    } else {
      await OrderItemApi.updateOrderItem(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    userId: undefined,
    orderId: undefined,
    cartId: undefined,
    spuId: undefined,
    spuName: undefined,
    properties: undefined,
    picUrl: undefined,
    count: undefined,
    commentStatus: undefined,
    price: undefined,
    discountPrice: undefined,
    deliveryPrice: undefined,
    adjustPrice: undefined,
    payPrice: undefined,
    couponPrice: undefined,
    pointPrice: undefined,
    usePoint: undefined,
    givePoint: undefined
  }
  formRef.value?.resetFields()
}
</script>
